package com.jusyl.cristo.auth.busi;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jusyl.cristo.auth.mapper.AuthOperationMapper;
import com.jusyl.cristo.auth.model.AuthRole;
import com.jusyl.cristo.auth.model.AuthUser;

@Service
public class AuthBusi {
	@Autowired
	AuthOperationMapper mapper;
	
	
	public int addUser(String name, String password) {
		AuthUser au = new AuthUser();
		au.setUsername(name);
		au.setPassword(password);
		
		return mapper.insertUser(au);
	}
	
	public List<AuthUser> getUsers() {
		
		return mapper.getUsers();
	}
	
	
	public int addRole(String roleName) {
		AuthRole ar = new AuthRole();
		ar.setRoleName(roleName);
		ar.setDesc("");
		return mapper.insertRole(ar);
	}
	
	public List<AuthRole> getRoles() {
		
		return mapper.getRoles();
	}
	
	public void login(String username, String password) {
		Map<String, Object> result = new HashMap<String, Object>();
        try{
            UsernamePasswordToken token = new UsernamePasswordToken(username, DigestUtils.md5Hex(password));  
            Subject currentUser = SecurityUtils.getSubject();  
            if (!currentUser.isAuthenticated()){
                //使用shiro来验证  
                token.setRememberMe(true);  
                currentUser.login(token);//验证角色和权限  
            } 
        }catch(Exception ex){
            ex.printStackTrace();
            throw ex;
        }
	}
	
	

	
}
